package com.kaigejava.rocketmq.controller.demo;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 凯哥Java
 * @description  发送异步消息
 * 发送异步消息：mq不会等待返回结果。会接着往下走
 * 异步消息可靠性没有同步消息可靠性高。
 * 异步消息，接受发送结果，是在sendCallback方法处理的
 * @company
 * @since 2022/10/18 18:09
 */
@RestController
public class AsyncProducerController {
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @GetMapping("/rocketmq/async-product/{message}")
    public String simpledSendMessage(@PathVariable("message") String normalMessage){
        for (int i = 0; i < 10; i++) {
            rocketMQTemplate.asyncSend("base-async-topic"
                    , MessageBuilder.withPayload("I'm from base-async-topic spring message" + i + normalMessage).build()
                    , new SendCallback() {
                        @Override
                        public void onSuccess(SendResult sendResult) {
                            System.out.println("异步发送消息,成功时候回调方法。%-10d ok %s %n."+sendResult.getMsgId());
                        }

                        @Override
                        public void onException(Throwable throwable) {
                            System.out.println("异步发送消息,异常回调方法."+throwable.getMessage());

                        }
                    });

        }
        return "异步消息发送完成。发送的消息为:"+normalMessage;
    }
}
